package com.kazusa.myservlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/fileDownload1")
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("文件下载");
        response.setContentType("text/html;charset=utf-8");
        //设置编码格式
        request.setCharacterEncoding("UTF-8");
        //获取参数
        String filename=request.getParameter("filename");
        //参数的非空判断
        if(filename==null||"".equals(filename.trim())){
            response.getWriter().write("请输入文件名");
            response.getWriter().close();
            return;
        }
        //得到图片的存放路径
        String path=request.getServletContext().getRealPath("/download/");
        //通过路径得到file对象
        File file=new File(path+filename);
        if(file.exists()&&file.isFile()){
            // 设置响应类型 (浏览器无法使用某种方式或激活某个程序来处理的类型)
            response.setContentType("application/x-msdownload");
            // 设置头信息
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            // 得到输入流
            InputStream  in=new FileInputStream(file);
            // 得到输出流
            ServletOutputStream os = response.getOutputStream();
            // 定义byte数组
            byte[] car = new byte[1024];
            // 定义长度
            int len = 0;
            // 循环输出
            while ((len = in.read(car)) != -1) {
                os.write(car, 0, len);
            }
            // 关闭流,释放资源
            os.close();
            in.close();
        }else {
            response.getWriter().write("文件不存在请重试");
            response.getWriter().close();
        }

    }
}
